<template>
    <div class="friendroom">
        <div class="top">
            <div class="name"> {{ friend.username }}</div>
            <el-icon class="elb" @click="drawer = true">
                <MoreFilled />
            </el-icon>
        </div>
        <div class="chat-records">

            <div v-for="(message, index) in userChatStore.chat_records" :key="index" class="message-wrapper"
                :class="{ 'sent': message.senderId === userStore.userId, 'received': message.senderId !== userStore.userId }">

                <!-- 显示头像 -->
                <div v-if="message.senderId !== userStore.userId" class="avatar">
                    <img :src="friend.avatar ?? ''" alt="avatar" />
                    <div class="message-content">
                        <div class="message-bubble">
                            <div class="message-text">{{ message.content }}</div>
                        </div>
                    </div>
                    <div class="timestamp">{{ message.timestamp }}</div>
                </div>

                <div v-else class="avatar">
                    <div class="timestamp">{{ message.timestamp }}</div>
                    <div class="message-content">

                        <div class="message-bubble">
                            <div class="message-text">{{ message.content }}</div>
                        </div>

                    </div>
                    <img :src="userStore.avatar ?? ''" />
                </div>
            </div>

        </div>
        <div class="bottom">
            <div class="input-wrapper">
                <input v-model="message" type="text" class="input-box" placeholder="请输入消息"
                    @keydown.enter="sendMessage" />
                <button class="send-btn" @click="sendMessage">发送</button>
            </div>
        </div>
    </div>
    <!-- 抽屉 -->
    <el-drawer v-model="drawer" :with-header="false" class="drawer" size="300">
        <div class="pic">
            <img :src="friend.avatar" alt="">
            <div class="name"> {{ friend.username }}</div>
        </div>

        <div class="notes" @click="getnotes">
            <div class="text">聊天记录</div>
            <el-icon color="#333" class="icon">
                <ArrowRight />
            </el-icon>
        </div>
        <div class="test5">
            <div class="item">
                <div class="text">消息免打扰</div>
                <el-switch size="small" />
            </div>
            <div class="item">
                <div class="text">置顶聊天</div>
                <el-switch size="small" />
            </div>
        </div>
        <div class="empty" @click="deletenotes">清空聊天记录</div>
    </el-drawer>
    <!-- 对话框 -->
    <!-- 聊天记录 -->
    <el-dialog v-model="dialogTableVisible" :title="friend.username" width="800" class="dialog">
        <div class="chat_records">
            <div class="search">
                <el-input placeholder="搜索" style="height: 40px;" @change="searchRecords(keyword)" v-model="keyword">
                    <template #prefix>
                        <el-icon class="el-input__icon">
                            <search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <!-- 遍历聊天记录 chat_records-->
            <div class="records" v-for="(record, index) in reversedChatRecords" :key="index">
                <!-- 用户头像 -->
                <div class="pic">
                    <!-- 如果聊天记录中的senderId==friend._id 头像为 friend.avatar，否则为userStore.avatar-->
                    <img :src="record.senderId === friend._id ? friend.avatar : userStore.avatar ?? ''"
                        alt="User Avatar">
                </div>
                <div class="info">
                    <div class="top">
                        <div class="name">{{ friend.username }}</div>
                        <div class="time">{{ record.timestamp }}</div>
                    </div>
                    <div class="content">{{ record.content }}</div>
                </div>
            </div>
        </div>
    </el-dialog>
    <!-- 删除聊天记录 -->
    <el-dialog v-model="dialogVisible" :modal="false" width="500">
        <!-- 由于聊天记录是单份存储,暂不写该功能 -->
        <span>删除聊天记录</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="deleteRecords">
                    清空
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { ref, reactive, watch } from 'vue';
import { useRoute } from 'vue-router';
import io from 'socket.io-client';
import type { chatData, UserData } from '../types/type'
//引入用户相关的仓库,获取当前用户的头像、昵称S
import useUserStore from '@/store/modules/user';
import useUserChatStore from '@/store/modules/userchat';
import { reqChatRecords, reqDeleteRecords } from '@/api/chat';
import { reqOneUserInfo } from '@/api/user';
import { formatDate } from '@/utils/time';
import { MoreFilled, ArrowRight, Search } from '@element-plus/icons-vue';
//获取存储用户信息的仓库对象
let userStore = useUserStore();
let userChatStore = useUserChatStore();
const route = useRoute();
// 好友id
let fid = ref()
// 房间名
let roomName=ref('')
let socket: any = null;
// 存储好友信息
let friend: UserData = reactive({
    _id: '',
    username: '',
    avatar: '',
})
// 获取键盘输入消息
let message = ref('')
let reversedChatRecords = ref<chatData[]>([]);
let keyword = ref<string>('');
// 控制抽屉
const drawer = ref(false)
// 打开聊天记录面板
const dialogTableVisible = ref(false)
// 打开聊天记录面板
const dialogVisible = ref(false)
// 发送消息
const sendMessage = async() => {
    if (message.value.trim() === '') return; // 检查消息是否为空
    const msg = {
        roomName: roomName.value, //指定接收消息的房间名称
        message: {
            content: message.value,
            senderId: userStore.userId,
            receiverId: fid.value,
            timestamp: new Date(), // 格式化时间
        },
    };
    const pushmessage={
            content: message.value,
            senderId: userStore.userId,
            receiverId: fid.value,
            timestamp: formatDate(msg.message.timestamp), // 格式化时间
    }
    // 发送消息到服务器
    socket.emit('sendMsg', msg);
    message.value = ''; // 清空输入框
    userChatStore.chat_records.push(pushmessage);//添加到聊天记录中
   await userChatStore.updatefriendChat(userStore.userId as string,roomName.value)
   console.log('发信息');
   
}

// 获取好友信息
const getfriendInfo = async () => {
    const result = await reqOneUserInfo(fid.value)
    if (result.code == 200) {
        friend = result.data
    }
}
onMounted(async () => {
    fid.value = route.params.id;
    roomName.value=route.params.roomName as string 
    await getfriendInfo()
    await userChatStore.getChatRecords(userStore.userId as string,roomName.value)
    await userChatStore.updatefriendChat(userStore.userId as string,roomName.value)
    socket = io('http://localhost:8080'); // 连接到你的 Socket.IO 服务器
    socket.on('connect', () => {
        console.log('Connected to Socket.IO server');
    });
    // 将信息已读
    console.log(2222);
    

})



// 监听fid切换房间
watch([() => route.params.id, () => route.params.roomName],async ([newId,newroomName]) => {
    console.log(newId,'切换房间');
    
    fid.value = newId;
    roomName.value=newroomName as string;
    await getfriendInfo();//先获取好友信息
    await userChatStore.getChatRecords(userStore.userId as string,roomName.value);//在获取聊天记录
    // 已读消息
});
// 聊天记录触发的事件
const getnotes = () => {
    // 打开聊天记录面板
    dialogTableVisible.value = true;
    // 获取聊天记录
    userChatStore.getChatRecords(userStore.userId as string,roomName.value);
    // 将聊天记录逆排序
    // 创建副本并逆序
    reversedChatRecords.value = [...userChatStore.chat_records].reverse();

}
// 删除聊天记录
const deletenotes = () => {
    // 打开是否删除记录的对话框
    dialogVisible.value = true;

}
// 搜索聊天记录
const searchRecords = async (keyword: string) => {

    // 获取聊天记录
    await userChatStore.getChatRecords(userStore.userId as string,keyword);
    // 将聊天记录逆排序
    // 创建副本并逆序
    reversedChatRecords.value = [...userChatStore.chat_records].reverse();
    console.log(keyword, '搜索');


}
// 删除所有聊天记录确定按钮触发的函数
const deleteRecords = async () => {
    const result = await reqDeleteRecords({ senderId: userStore.userId, receiverId: fid.value })
    console.log(result);
    dialogVisible.value = false

}
</script>

<style scoped lang="scss">
.img {
    width: 100%;
    height: 100%;
    text-align: center;
    padding: 200px;
}

.friendroom {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #f1f1f1;

    .top {
        display: flex;
        width: 100%;
        height: 70px;
        background-color: #f1f1f1;
        border-bottom: 1.5px solid #E0E0E0;
        padding-left: 30px;
        align-items: center;

        /* 垂直居中对齐 */
        .name {
            font-size: 24px;

        }

        .elb {
            margin-left: auto;
            /* 将按钮推到右边 */
            margin-right: 25px;

            &:hover {
                color: #5b8ef5;
            }
        }
    }

    .chat-records {
        margin-bottom: 70px;
        padding: 10px;
        min-height: calc(100% - 140px);
        max-height: calc(100% - 140px);
        overflow-y: scroll;

        .message-wrapper {
            display: flex;
            margin-bottom: 35px;
            align-items: flex-end;

            .avatar {
                position: relative;
                display: flex;
                align-items: center;

                img {
                    max-width: 40px;
                    height: 40px;
                    margin: 0 10px;
                    object-fit: cover;
                }
            }

            .message-content {
                max-width: 100%;

                .message-bubble {
                    max-width: 500px;
                    background-color: #f1f1f1;
                    border-radius: 15px;
                    padding: 6px 10px;
                    font-size: 14px;
                    line-height: 20px;
                }


            }



            &.sent {
                justify-content: flex-end;

                .timestamp {
                    width: 150px;
                    position: absolute;
                    top: 40px;
                    right: 80px;
                    font-size: 12px;
                    color: #aaa;
                    text-align: right;
                    margin-top: 3px;
                }

                .message-bubble {
                    background-color: #5b8ef5;
                    color: #fff;
                }
            }

            &.received {
                justify-content: flex-start;

                .timestamp {
                    width: 150px;
                    position: absolute;
                    top: 40px;
                    left: 40px;
                    font-size: 12px;
                    color: #aaa;
                    text-align: right;
                    margin-top: 3px;
                }

                .message-bubble {
                    background-color: #fff;

                }
            }
        }
    }

    .bottom {
        width: 100%;
        position: absolute;
        bottom: 0;
        right: 0;
        padding: 10px;
        background-color: #f1f1f1;
        border-top: 1px solid #e0e0e0;

        .input-wrapper {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 5px;
            border-radius: 20px;
            background-color: #f1f1f1;

            .input-box {
                flex-grow: 1;
                padding: 8px 12px;
                border: none;
                border-radius: 20px;
                background-color: #fff;
                font-size: 14px;
                outline: none;

                ::placeholder {
                    color: #bbb;
                }
            }

            .send-btn {
                margin-left: 10px;
                padding: 8px 12px;
                border: none;
                background-color: #07c160;
                color: #fff;
                font-size: 14px;
                border-radius: 20px;
                cursor: pointer;

                &:hover {
                    background-color: #05a24f;
                }
            }
        }
    }
}

.drawer {
    .pic {
        height: 100px;
        width: 100%;
        text-align: center;
        padding-left: 15px;
        border-bottom: 1px solid #E0E0E0;
        padding-bottom: 10px;

        .name {

            font-size: 13px;
            text-align: center;

            margin-top: 5px;
        }

        img {
            text-align: center;
            width: 50px;
            height: 50px;
            object-fit: cover;
        }
    }



    .notes {

        border-bottom: 1px solid #E0E0E0;
        height: 50px;
        display: flex;

        .text {
            height: 50px;
            line-height: 50px;
            font-size: 14px;
            width: 250px;
        }

        .icon {
            height: 50px;
            line-height: 50px;
            font-size: 14px;

        }
    }

    .test5 {
        margin-top: 30px;
        height: 100px;
        border-bottom: 1px solid #E0E0E0;

        .item {
            display: flex;
            height: 30px;

            .text {
                height: 30px;
                font-size: 14px;
                line-height: 30px;
                width: 230px;
            }
        }
    }

    .empty {
        // border-top: 1px solid #E0E0E0;
        font-size: 14px;
        height: 45px;
        text-align: center;
        color: red;
        line-height: 45px;
    }

}

.dialog {
    .chat_records {
        max-height: 500px;
        /* 设置最大高度，超过则出现滚动条 */
        overflow-y: auto;

        .search {
            position: sticky;
            /* 固定在顶部 */
            top: 0;
            /* 距离顶部 0 */
            z-index: 1;
            /* 保证搜索框位于聊天记录的上方 */
        }

        /* 使内容在超出时垂直滚动 */
        .records {
            padding: 15px;
            width: 100%;
            min-height: 80px;
            display: flex;

            &:hover {
                background-color: #E0E0E0;
                /* 鼠标悬停时的背景颜色 */
            }

            .pic {
                width: 6%;
                height: 100%;

                img {

                    width: 40px;
                    height: 40px;
                    object-fit: cover;
                }



            }

            .info {
                width: 94%;
                padding-left: 5px;

                .top {
                    display: flex;
                    font-size: 12px;
                    justify-content: space-between;
                    /* 将子元素分散对齐，左右分开 */
                    align-items: center;

                    /* 垂直居中对齐 */

                }

                .content {
                    font-size: 14px;
                    padding-top: 30px;
                    width: 88%;
                    color: #000;
                    border-bottom: 1px solid #E0E0E0;
                    min-height: 70px;
                }

            }
        }
    }


}
</style>